package user

import (
	"context"
	"time"

	"emperror.dev/errors"
	"git.bybit.com/svc/go/pkg/bzap"
	"git.bybit.com/svc/mod/pkg/bproto"
	"git.bybit.com/svc/stub/pkg/pb/api/user"
)

type Usvc = *usvc

type usvc struct {
	u user.MemberInternalClient
}

func NewUsvcClient(u user.MemberInternalClient) Usvc {
	return &usvc{
		u: u,
	}
}

func (c *usvc) GetBrokerByMemberID(ctx context.Context, memberID int64) (*user.Broker, error) {
	userSvcCtx, cancel := bzap.TracedTimeoutContext(ctx, 2*time.Second)
	defer cancel()

	req := &user.GetBrokerByMemberIDRequest{
		MemberId: memberID,
	}
	resp, err := c.u.GetBrokerByMemberID(userSvcCtx, req)
	if err != nil {
		return nil, errors.WithMessage(err, "GetBrokerByMemberID Fail")
	}

	if !bproto.Ok(resp.Error) {
		err = bproto.StatusErrorFromCommonError(resp.Error)
		return nil, err
	}

	return resp.Broker, nil
}
